package com.whz.practise.ui.customView

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import com.whz.practise.R


/**
 *@auther whz
 *@date 2021/4/11 15:41
 */
class MyTextView : View {

    private var mText: String = ""

    private var mTextSize: Int = 16//px

    private var mColor: Int = Color.BLACK

    var mPaint: Paint? = null

    //三个构造函数必须都有 不然报错 ？？？
    constructor(context: Context) : this(context, null)
    constructor(context: Context, attributeSet: AttributeSet? = null) : this(context, attributeSet, 0)
    constructor(context: Context, attributeSet: AttributeSet? = null, defStyleAttr: Int) : super(context, attributeSet, defStyleAttr) {
        //获取自定义属性
        val array = context.obtainStyledAttributes(attributeSet, R.styleable.MyTextView)
        mText = array.getString(R.styleable.MyTextView_myText)!!
        mColor = array.getColor(R.styleable.MyTextView_myTextColor, mColor)
        mTextSize = array.getDimensionPixelSize(R.styleable.MyTextView_myTextSize, sp2px(mTextSize))
        mPaint = Paint()
        mPaint!!.isAntiAlias = true//抗锯齿
        mPaint!!.setColor(Color.parseColor("#E91E63"))
        mPaint!!.textSize = mTextSize.toFloat()

        //回收
        array.recycle()
    }

    /**
     *
     */
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        var widthMode = MeasureSpec.getMode(widthMeasureSpec)
        var heightMode = MeasureSpec.getMode(heightMeasureSpec)

        var width = MeasureSpec.getSize(widthMeasureSpec)
        var height = MeasureSpec.getSize(heightMeasureSpec)

        if (widthMode == MeasureSpec.AT_MOST) {
            val bounds = Rect()
            mPaint!!.getTextBounds(mText, 0, mText.length, bounds)
            width = bounds.width()+paddingLeft+paddingRight
        }

        if (heightMode == MeasureSpec.AT_MOST) {
            val bounds = Rect()
            mPaint!!.getTextBounds(mText, 0, mText.length, bounds)
            height= bounds.height()+paddingTop+paddingBottom
        }

        setMeasuredDimension(width, height)
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        //基线
        val fm=mPaint!!.fontMetrics
        var dy=(fm.bottom-fm.top)/2-fm.bottom
        val baseLineY=height/2+dy
        canvas!!.drawText(mText, paddingLeft.toFloat(), baseLineY, mPaint!!)
    }

    //    sp转px
    fun sp2px(sp: Int): Int {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp.toFloat(), context.getResources().getDisplayMetrics()).toInt()
    }
}